using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using Light;
using Light.Assets.Scripts.EventManager;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Dream.FirstLevel
{
    //mao 24-11-28 04:37
    /// <summary>
    ///     在场景中生成Boss
    /// </summary>
    public class BossController : MonoBehaviour
    {
        [Header("存在的所有Boss")] [SerializeField] private List<GameObject> _bossList = new();

        [Header("实例化Boss的地点")] [SerializeField]
        private List<Transform> _bossSpawnPoints = new();

        [Header("波次总数和每个波次的老板数量")] [SerializeField]
        private List<int> _wavesList = new();


        [Header("波次中boss的生随机间隔")] [Header("最短等待时间")] [SerializeField]
        private float _minWaitTime;

        [Header("最长等待时间")] [SerializeField] private float _maxWaitTime;

        /// <summary>
        ///     已经被使用出生点
        ///     <para>在波次结束后一定要进行清理</para>
        /// </summary>
        private readonly List<int> _usedBossSpawnPointIndex = new();


        /// <summary>
        ///     检查当前活跃的boss游戏对象
        /// </summary>
        private int _curActiveBossAmount;

        private int haveCreatedBossAmount;

        //mao 24-11-28 05:43
        /// <summary>
        ///     通过EventManager进行控制进入到下一个波次的标准
        /// </summary>
        private bool isEnterNextWave;

        //可重复指定的倒计时
        private Timer timer;

        public int CurActiveBossAmount
        {
            get => _curActiveBossAmount;
            set
            {
                if (value == 0) WaveClearAndCreate();
                _curActiveBossAmount = value;
            }
        }

        /// <summary>
        ///     当前正在使用的波次在数组中的索引
        /// </summary>
        public int CurActiveWaveIndex { get; set; }

        private void Awake()
        {
            EventManager.Register<BossDestroyEvent>(OnBossDestroyEventHandle);
            EventManager.Register<EnterNextWaveEvent>(OnEnterNextWaveEventHandle);
            timer = new Timer(OnTimeDownEventHandle);
        }


        private void Start()
        {
            //第一次生成Boss默认等待3秒
            timer.SetDurationTime(3);
            timer.StartTimer();
        }

        private void OnDestroy()
        {
            EventManager.Unregister<BossDestroyEvent>(OnBossDestroyEventHandle);
            EventManager.Unregister<EnterNextWaveEvent>(OnEnterNextWaveEventHandle);

            timer.RemoveActionListener();
        }

        private void OnBossDestroyEventHandle(BossDestroyEvent obj)
        {
            --CurActiveBossAmount;
        }

        private void OnEnterNextWaveEventHandle(EnterNextWaveEvent obj)
        {
            isEnterNextWave = true;
        }


        /// <summary>
        ///     boss生成的波次清理以及下回合的boss生成
        /// </summary>
        private async UniTaskVoid WaveClearAndCreate()
        {
            ++CurActiveWaveIndex;
            //最总波次检测
            if (CurActiveWaveIndex >= _wavesList.Count)
            {
                //发送切换场景的请求
                using var evt1 = NextSceneLoad.Get();
                evt1.isFadeScreen = true;
                evt1.isExitScene = true;
                EventManager.SendEvent(evt1);

                //返回不去执行下面内容
                return;
            }


            _usedBossSpawnPointIndex.Clear();
            haveCreatedBossAmount = 0;

            //打开UI
            using var evt = OpenSummaryPanelEvent.Get();
            EventManager.SendEvent(evt);

            //等待UI输入
            Time.timeScale = 0f;
            await UniTask.WaitUntil(() => isEnterNextWave);
            Time.timeScale = 1f;
            isEnterNextWave = false;


            //启动Boss生成倒计时
            timer.SetDurationTime(3);
            timer.StartTimer();
        }

        //mao 24-11-28 05:17
        /// <summary>
        ///     开始实例化Boss并准备下一个Boss的生成
        /// </summary>
        private void OnTimeDownEventHandle()
        {
            timer.StopTimer();
            //检查允许生成
            if (haveCreatedBossAmount < _wavesList[CurActiveWaveIndex])
            {
                Random.InitState((int)Time.time);
                var radomIndexOfBoss = Random.Range(0, _bossList.Count);
                while (true)
                {
                    Random.InitState((int)Time.time + 10);
                    var randomIndexOfSpawnPoint = Random.Range(0, _bossSpawnPoints.Count);

                    //一个波次中的出生点不允许重复
                    if (_usedBossSpawnPointIndex.Contains(randomIndexOfSpawnPoint)) continue;

                    //生成Boss并跳出循环
                    Instantiate(_bossList[radomIndexOfBoss], _bossSpawnPoints[randomIndexOfSpawnPoint]);
                    _usedBossSpawnPointIndex.Add(randomIndexOfSpawnPoint);
                    CurActiveBossAmount++;
                    haveCreatedBossAmount++;
                    break;
                }

                //准备下一个boss的生成
                Random.InitState((int)Time.time);
                timer.SetDurationTime(Random.Range(_minWaitTime, _maxWaitTime));
                timer.StartTimer();
            }
        }
    }
}